package com.shop.servlet.client;

import com.shop.comment.Constants;
import com.shop.config.JedisConfig;
import com.shop.entity.User;
import com.shop.entity.VO.CarVo;
import com.shop.service.GoodsService;
import com.shop.service.GoodsServiceImpl;
import com.shop.service.UserService;
import com.shop.service.UserServiceImpl;
import com.shop.util.SMSUtil;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;
import java.util.Random;

@WebServlet(name = "UserServlet",urlPatterns = "/UserServlet")
public class UserServlet extends HttpServlet {

	UserService userService = new UserServiceImpl();

	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doGet(request, response);
	}

	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		request.setCharacterEncoding("utf-8");
		//获取请求的类型==》action / opr / type
		String action = request.getParameter("action");
		switch (action){
			case "login":
				login(request, response);
				break;
			case "regist":
				regist(request, response);
				break;
			case "sms":
				sms(request, response);
				break;
			case "smslogin":
				smsLogin(request, response);
				break;
			case "quit":
				quit(request, response);
				break;
		}
	}

	//手机短信验证码登入
	private void smsLogin(HttpServletRequest request, HttpServletResponse response) throws IOException {
		//获取手机号码
		String phone = request.getParameter("phone");
		String code = request.getParameter("code");
		//手机号码的验证码是否正确==>在redis缓存中查找是否有信息
		int ret = 0; //正常
		JedisConfig redis = new JedisConfig();
	    String rediscode =redis.get(Constants.RedisInfo.PREFIX_SMS_CODE+phone);
	    if(rediscode==null || !rediscode.equals(code)){
	    	//验证失败
		    System.out.println("验证码输入错误。。");
		    ret = 1;//验证码错误

	    }else{
	    	//成功登入后，清空缓存中的数据
		    redis.delete(rediscode);
	    }
		//数据库中是否有匹配的手机号==》账户==>待完成
		User user = userService.findUserByPhone(phone);
	    loginSuccess(user, request);
		//响应
		PrintWriter out = response.getWriter();
		out.print(ret);
		out.flush();
		out.close();
	}

	//短信
	private void sms(HttpServletRequest request, HttpServletResponse response) throws IOException {
		//获取手机号码
		String phone = request.getParameter("phone");
		//发送短信
		Random random = new Random();
		Integer phoneCode = random.nextInt(9000)+1000;

		//将发送的短信验证码保存到redis中==》key==》login_phone_code_电话号码
		JedisConfig redis = new JedisConfig();
		//判断是否已发送短信验证码==》还未过期，则不能重新发送短信
		boolean isExist = redis.exist(Constants.RedisInfo.PREFIX_SMS_CODE);
		if (isExist){
			return ;
		}

		boolean bool =  SMSUtil.sendSMS(phone,phoneCode.toString()); //发短信
		System.out.println("电话号码："+phone+" 验证码："+phoneCode +" "+bool);
		if(bool){
			redis.set(Constants.RedisInfo.PREFIX_SMS_CODE+phone,
					phoneCode.toString(),
					Constants.RedisInfo.EXPIRE_TIME_SMS_CODE);
		}
		//响应
		PrintWriter out = response.getWriter();
		out.print(bool);
		out.flush();
		out.close();
	}

	//登入
	public void login(HttpServletRequest request, HttpServletResponse response) throws IOException {
		//账号，密码
		String account = request.getParameter("account");
		String password = request.getParameter("password");
		//调用方法
	    User user =  userService.findUserByAccount(account);
		//页面跳转/ 响应
		String msg = "";
		if(user == null){
			msg = "账号不存在";
		}else if(!user.getPassword().equals(password)){
			msg = "密码不正确";
		}else{
			msg = "ok";
			//判断是否记住我==》需要将数据放入cookie

			//登入成功
			loginSuccess(user, request);

		}

		response.setCharacterEncoding("utf-8");
		response.setContentType("text/html;charset=UTF-8");
		//响应
		PrintWriter out = response.getWriter();
		out.print(msg);
		out.flush();
		out.close();
	}


	//记住我
	public void remenberMe(HttpServletRequest request,HttpServletResponse response,User loginUser){
		//将登入用户信息，存在Cookie中
	}

	//登入成功
	private void loginSuccess(User user,HttpServletRequest request){
		//绑定购物车数据【cookie / 缓存中 /数据库】 ==》user_car_id/acount
		JedisConfig redeis = new JedisConfig();
		//String car = "744-1_736-3_742-1"; //商品编号-数量
		String car = redeis.get(Constants.RedisInfo.LOGIN_USER_CAR+user.getId());
		GoodsService goodsService = new GoodsServiceImpl();
		List<CarVo> carVoList = goodsService.findCarVo(car);
		// 登入用户信息==》session
		request.getSession().setAttribute("carList",carVoList);
		request.getSession().setAttribute("loginUser", user);
	}


	//退出
	public void quit(HttpServletRequest request,HttpServletResponse response) throws IOException {
		request.getSession().removeAttribute("loginUser");
		response.sendRedirect("client/Login.jsp");
	}

	//注册
	public void regist(HttpServletRequest request, HttpServletResponse response) throws IOException {
		 String account = request.getParameter("account");        //登录名称
		 String nickName= request.getParameter("nickName");    //用户名
		String gender= request.getParameter("gender");    //用户名
		 String password= request.getParameter("password");   //密码
		 String email= request.getParameter("email");       //电子邮箱
		 String phone = request.getParameter("phone");      //电话

		User reg = new User(account, nickName, password, email, phone);
		reg.setGender(Integer.valueOf(gender));

		//调用
		int ret = userService.add(reg);
		if(ret >0 ){
			response.sendRedirect("client/Login.jsp");
		}else{
			PrintWriter out = response.getWriter();
			out.print("<script type='text/javascript'>history.back();</script>");
			out.flush();
			out.close();
		}

	}




}
